﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using OpenQuarters.WebQuarters.Core;
using OpenQuarters.WebQuarters.Utils;
using OpenQuarters.WebQuarters.Modules.ItemList;
using System.Xml.Serialization;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace OpenQuarters.WebQuarters.Modules.ItemSearch
{
    public class ItemSearchForm : ItemSearchModule
    {
        private string postAction = "/cms/modules/MethodHandler/OpenQuarters.WebQuarters.Modules.ItemSearch,ItemSearchModule,AjaxSearchHandler";

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public string Post_Action
        {
            get { return postAction; }
            set { postAction = value; }
        }

        private string postNoScriptAction = Oracle.Request.Url.ToString();

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public string No_Script_Post_Action
        {
            get { return postNoScriptAction; }
            set { postNoScriptAction = value; }
        }

        public ItemSearchForm()
            : base()
        {
        }

        public override void Initialise()
        {
            this.ModuleName = "Item Search Module - Form";
            this.ModuleDescription = "Provides a search form";
        }

        public override string GetJQueryEditorName()
        {
            return "cmsModuleEditor";
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (Core.User.Current.HasPermission(Permissions.CMSPage.Edit.SetValue(CMSPage.Current.PageId.ToString())))
            {
                // We are using the content module editor with a custom onSetup and onSave methods for inline editing of entity fields
                JavaScript.RegisterScript("Modules.Content.AdminScript.js", "OpenQuarters.WebQuarters.Modules.Core", "Resources.Content.AdminScript.js", JavaScriptType.AdminScript);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (Request.Headers["Accept"] != null && Request.Headers["Accept"].IndexOf("application/json") != -1)
            {
                // Do nothing if json request
            }
            else
            {
                if (!string.IsNullOrEmpty(base.Full_View_Page))
                {
                    CMSPage page = CMSPage.Load(Convert.ToInt32(base.Full_View_Page));
                    // Create search form
                    if (base.Search_Form.IndexOf(",") == -1 && System.IO.File.Exists(Server.MapPath("~/Forms/" + base.Search_Form + ".tpl")))
                    {
                        if (base.Use_Javascript)
                        {
                            JavaScript.RegisterScript("SearchHandler", "OpenQuarters.WebQuarters.Modules.ItemSearch", "Resources.SearchHandler.js", JavaScriptType.PageScript);

                            XmlSerializer Serializer = new XmlSerializer(typeof(ItemListerConfiguration));
                            StringWriter configStream = new StringWriter();
                            Serializer.Serialize(configStream, base.Config);
                            Utils.Encryption.SimpleAES aes = new Encryption.SimpleAES();
                            string encyptedOptions = aes.EncryptToString(configStream.ToString());

                            if (page != null && Request.Url.AbsoluteUri.IndexOf("/site/" + page.CurrentVersion.CMSPage.Urls[0].PageUrl) != -1)
                            {
                                // Perform on page search 
                                this.Controls.Add(new JForm(base.Search_Form, this.postAction, this.postNoScriptAction, new { cmsEnv_ItemType = this.ItemType, cmsEnv_options = encyptedOptions, cmsEnv_MainView = this.Main_View })
                                {
                                    UseJavaScript = true,
                                    OnLoadedScript = (!string.IsNullOrEmpty(this.On_Loaded_Script) ? this.On_Loaded_Script : ""),
                                    OnSuccessScript = (!string.IsNullOrEmpty(base.On_Success_Script) ? base.On_Success_Script : "ItemSearchModule_HandleResults(response)"),
                                    OnProceedScript = (!string.IsNullOrEmpty(base.On_Success_Script) ? base.On_Proceed_Script : ""),
                                    Method = JFormControl<DefaultJFormClass>.MethodType.GET
                                });
                            }
                            else
                            {
                                // Search form not on results page so post to page search results page
                                this.Controls.Add(new JForm(base.Search_Form, this.postAction, this.postNoScriptAction)
                                {
                                    UseJavaScript = false,
                                    Method = JFormControl<DefaultJFormClass>.MethodType.GET
                                });
                            }
                        }
                        else
                        {
                            // Post to search results page (without js)
                            this.Controls.Add(new JForm(base.Search_Form, this.postAction, this.postNoScriptAction)
                            {
                                UseJavaScript = false,
                                Method = JFormControl<DefaultJFormClass>.MethodType.GET
                            });
                        }
                    }
                    else
                    {
                        this.Controls.Add(new JForm(base.Search_Form, JForm.TemplateType.EmbeddedResource, this.postAction, this.postNoScriptAction)
                        {
                            UseJavaScript = base.Use_Javascript,
                            Method = JFormControl<DefaultJFormClass>.MethodType.GET
                        });
                    }
                }
                else
                {
                    if (Core.User.Current.HasPermission(Permissions.CMSPage.Edit.SetValue(CMSPage.Current.PageId.ToString())))
                        this.Controls.AddLiteral("Double click to edit Search Module Form");
                }
            }
        }
    }
}
